<template>
  <div :class="{
          'at-tabs': true,
          'at-tabs--card': type === 'card',
          'at-tabs--border-card': type === 'border-card'}">
    <div class="at-tabs__header">
      <span class="at-tabs__new-tab" @click="handleTabAdd" v-if="editable || addable">
        <i class="at-icon-plus"></i>
      </span>
      <tab-nav ref="nav" :currentName="currentName" :onTabClick="handleTabClick" :onTabRemove="handleTabRemove" :editable="editable" :type="type" :panes="panes"></tab-nav>
    </div>
    <div class="at-tabs__content">
      <slot></slot>
    </div>
  </div>

</template>
<script>
  import TabNav from './tab-nav'
  export default {
    name: 'MhTabs',

    components: {
      TabNav
    },

    props: {
      type: String,
      activeName: String,
      closable: Boolean,
      addable: Boolean,
      value: {},
      editable: Boolean
    },

    data () {
      return {
        currentName: this.value || this.activeName,
        panes: []
      }
    },

    watch: {
      activeName (value) {
        this.setCurrentName(value)
      },
      value (value) {
        this.setCurrentName(value)
      },
      currentName (value) {
        if (this.$refs.nav) {
          this.$nextTick(_ => {
            this.$refs.nav.scrollToActiveTab()
          })
        }
      }
    },

    methods: {
      handleTabClick (tab, tabName, event) {
        if (tab.disabled) return
        this.setCurrentName(tabName)
        this.$emit('tab-click', tab, event)
      },
      handleTabRemove (pane, ev) {
        if (pane.disabled) return
        ev.stopPropagation()
        this.$emit('edit', pane.name, 'remove')
        this.$emit('tab-remove', pane.name)
      },
      handleTabAdd () {
        this.$emit('edit', null, 'add')
        this.$emit('tab-add')
      },
      setCurrentName (value) {
        this.currentName = value
        this.$emit('input', value)
      },
      addPanes (item) {
        const index = this.$slots.default.indexOf(item.$vnode)
        this.panes.splice(index, 0, item)
      },
      removePanes (item) {
        const panes = this.panes
        const index = panes.indexOf(item)
        if (index > -1) {
          panes.splice(index, 1)
        }
      }
    },
    created () {
      if (!this.currentName) {
        this.setCurrentName('0')
      }
    }
  }
</script>